<style lang="less">
    @import "./course.less";
</style>
<template>
    <div class="search">
        <Row>
            <Col>
            <Card>
                <p slot="title">
                    <span v-if="type==0">创建课程</span>
                    <span v-else>编辑课程</span>
                </p>
                <Row>
                    <Form ref="form" :model="form" :label-width="70" :rules="formValidate" style="position:relative">
                        <FormItem label="课程类型" prop="onLine">
                            <RadioGroup v-model="form.onLine">
                                <Radio label="1">线上课程</Radio>
                                <Radio label="0">线下课程</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem label="课程名称" prop="courseTitle">
                            <Input v-model="form.courseTitle" style="width:600px"/>
                        </FormItem>
                        <FormItem label="课程介绍" prop="courseContent">
                            <div ref="editor"></div>
                        </FormItem>
                        <Form-item label class="br">
                            <Button @click="editHTML" icon="ios-create-outline">编辑HTML代码</Button>
                            <Button @click="fullscreenModal=true" icon="md-eye">预览</Button>
                        </Form-item>
                        <FormItem label="封面图" prop="courseImage">
                            <upload-input :fileUrl="form.courseImage" @on-change="handleUpload" width="400px" ref="upload"></upload-input>
                        </FormItem>
                        <FormItem label="课程价格" prop="coursePrice">
                            <InputNumber :max="10000" :precision="2" :min="0" v-model="form.coursePrice" :formatter="value  => `¥ ${value }`.replace(/B(?=(d{3})+(?!d))/g, ',')" :parser="value => value.replace(/¥s?|(,*)/g, '')"></InputNumber>
                            <span style="padding-left: 20px;">
                                     会员免费
                                <RadioGroup v-model="form.isVipFree">
                                    <Radio label=0>是</Radio>
                                    <Radio label=1>否</Radio>
                                </RadioGroup>
                                 </span>
                        </FormItem>

                        <FormItem label="上课地址" prop="courseAddress" v-if="form.onLine==0">
                            <Input v-model="form.courseAddress" icon="md-locate" placeholder="请输入上课地址" style="width:600px"/>
                        </FormItem>
                        <FormItem label="上课时间" prop="courseBeginDate" v-if="form.onLine==0">
                            <Input v-model="form.courseBeginDate" style="width:600px"/>
                        </FormItem>
                        <FormItem label="选择讲师">
                            <user-choose buttonText="选择讲师" @on-change="handleSelectUser" ref="user"></user-choose>
                        </FormItem>
                        <Form-item class="br">
                            <Button type="primary" :loading="submitLoading" @click="handelSubmit" style="width:100px">提交</Button>
                            <Button @click="handelCancel">取消</Button>
                        </Form-item>
                        <Spin size="large" fix v-if="loading"></Spin>
                    </Form>
                </Row>
            </Card>
            </Col>
        </Row>
        <!-- html编辑 -->
        <Modal title="编辑html代码" v-model="showHTMLModal" :mask-closable="false" :width="900" :fullscreen="full">
            <Input v-if="!full" v-model="dataEdit" :autosize="true" type="textarea" style="max-height:60vh;overflow:auto"/>
            <Input v-if="full" v-model="dataEdit" :autosize="true" type="textarea"/>
            <div slot="footer">
                <Button @click="full=!full" icon="md-expand">全屏开/关</Button>
                <Button @click="editHTMLOk" type="primary" icon="md-checkmark-circle-outline">确定保存</Button>
            </div>
        </Modal>
        <Modal title="预览" v-model="fullscreenModal" fullscreen>
            <div v-html="form.courseContent">{{form.courseContent}}</div>
            <div slot="footer">
                <Button @click="fullscreenModal=false">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {uploadFile} from "@/api/index";
    import {addCrouse,editCourse,getCourse} from "@/api/bus";
    import userChoose from "../../my-components/flyme/user-choose";
    import uploadInput from "@/views/my-components/flyme/upload-input";
    import E from "wangeditor";
    // 表情包配置 自定义表情可在该js文件中统一修改
    import {sina} from "@/libs/emoji";


    let editor = null;
    var xss = require("xss");
    export default {
        name: "add_course",
        components: {
            userChoose,
            uploadInput
        },
        data() {
            return {
                type: 0,
                loading: false, // 表单加载状态
                selectUsers: [],
                userModalVisible: false,
                modalTitle: "", // 添加或编辑标题
                form: {
                    // 添加或编辑表单对象初始化数据
                    courseTitle: "",
                    courseContent: "",
                    onLine: "1",
                    isVipFree: "1",
                    courseBeginDate: "",
                    courseAddress: "",
                    courseImage: "",
                    coursePrice: "",
                    range: 0
                },
                formValidate: {
                    // 表单验证规则
                    courseTitle: [{required: true, message: "课程名称不能为空", trigger: "blur"}],
                    coursePrice: [{required: true, message: "课程价格不能为空", trigger: "blur"}],
                    courseContent: [{required: true, message: "课程介绍不能为空", trigger: "blur"}]
                },
                submitLoading: false, // 添加或编辑提交状态
                dictMessageType: [],
                dictSex: [],
                dataEdit: "", // 编辑数据
                showHTMLModal: false, // 显示html
                full: false, // html全屏开关
                fullscreenModal: false, // 显示全屏预览
                backRoute: ""
            };
        },
        methods: {
            init() {
                this.initEditor();
                this.type = this.$route.query.type;
                this.backRoute = this.$route.query.backRoute;
                if (this.type == 1) {
                    this.form.id = this.$route.query.courseId;
                    this.getData();
                }
            },
            initEditor() {
                let that = this;
                editor = new E(this.$refs.editor);
                editor.customConfig.onchange = html => {
                    this.form.courseContent =html;
                };
                editor.customConfig.uploadImgServer = uploadFile;
                editor.customConfig.uploadImgHeaders = {
                    Authorization: that.getStore("accessToken")
                };
                editor.customConfig.uploadFileName = "file";
                editor.customConfig.uploadImgHooks = {
                    before: function (xhr, editor, files) {
                    },
                    success: function (xhr, editor, result) {
                    },
                    fail: function (xhr, editor, result) {
                        that.$Message.error("上传图片失败");
                    },
                    error: function (xhr, editor) {
                        that.$Message.error("上传图片出错");
                    },
                    timeout: function (xhr, editor) {
                        that.$Message.error("上传图片超时");
                    },
                    customInsert: function (insertImg, result, editor) {
                        if (result.status === true) {
                            let url = result.data.fileUrl;
                            insertImg(url);
                            that.$Message.success("上传图片成功");
                        } else {
                            that.$Message.error(result.info);
                        }
                    }
                };
                editor.customConfig.fontNames = ["微软雅黑", "宋体", "黑体", "Arial"];
                editor.customConfig.emotions = [
                    {
                        title: "新浪",
                        type: "image",
                        content: sina
                    }
                ];
                editor.create();
            },
            editHTML() {
                this.dataEdit = this.form.courseContent;
                this.showHTMLModal = true;
            },
            editHTMLOk() {
                editor.txt.html(this.dataEdit);
                this.form.courseContent = xss(this.dataEdit);
                this.showHTMLModal = false;
            },
            getData() {
                this.loading = true;
                getCourse(this.form.id).then(res => {
                    this.loading = false;
                    if (res.status === true) {
                        editor.txt.html(res.data.courseContent);
                        this.form = data;
                    }
                });
            },
            handelSubmit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.submitLoading = true;
                        if (this.type === 0) {
                            // 添加 避免编辑后传入id等数据 记得删除
                            delete this.form.id;
                            // 用户id数据
                            let ids = [];
                            this.selectUsers.forEach(e => {
                                ids.push(e.id);
                            });
                            this.form.lecturerId = ids;
                            addCrouse(this.form).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("操作成功");
                                    this.closeCurrentPage();
                                }
                            });
                        } else if (this.type === 1) {
                            // 编辑
                            editCourse(this.form).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("操作成功");
                                    this.closeCurrentPage();
                                }
                            });
                        }
                    }
                });
            },
            handleSelectUser(v) {
                this.selectUsers = v;
            },
            handelCancel() {
                this.closeCurrentPage();
            },
            handleUpload(v) {
                this.courseImage = v.fileUrl;
            },
            // 关闭当前页面
            closeCurrentPage() {
                this.$store.commit("removeTag", "add_course");
                localStorage.pageOpenedList = JSON.stringify(
                    this.$store.state.app.pageOpenedList
                );
                this.$router.push({
                    name: this.backRoute
                });
            }
        },
        mounted() {
            this.init();
        },
        watch: {
            // 监听路由变化
            $route(to, from) {
                if (to.name == "add_course") {
                    this.type = this.$route.query.type;
                    if (this.type == 1) {
                        this.form.id = this.$route.query.courseId;
                        this.getData();
                    }
                }
            }
        }
    };
</script>